package com.yonyou.cyxdms.basedata.client.service.basedata;

import com.yonyou.cyx.framework.bean.dto.base.ClientInfoDTO;
import com.yonyou.cyx.framework.compent.redis.RedisClient;
import com.yonyou.cyx.framework.util.bean.ApplicationContextHelper;
import com.yonyou.cyx.function.utils.common.CommonUtils;
import com.yonyou.cyx.function.utils.common.StringUtils;
import com.yonyou.cyx.function.utils.jsonserializer.JSONUtil;
import com.yonyou.cyxdms.basedata.client.constants.BaseDataCommonConstants;
import com.yonyou.cyxdms.basedata.client.domains.vo.ColorCacheCMSVO;
import com.yonyou.cyxdms.basedata.client.domains.vo.ColorCacheVO;
import com.yonyou.cyxdms.basedata.client.feign.BaseDataCommonClient;
import com.yonyou.cyxdms.basedata.client.util.ConditionMapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.util.List;
import java.util.Map;

/**
 * 颜色
 *
 * @author renwd
 * @since 2018/12/18
 */

@Service
public class BaseCommonColorServiceImpl implements BaseCommonColorService {

    private final Logger logger = LoggerFactory.getLogger(BaseCommonModelServiceImpl.class);

    @Autowired
    private BaseDataCommonClient baseDataCommonClient;

    @Autowired
    private RedisClient redisClient;

    /**
     * 根据配置id、颜色id查询颜色信息
     *
     * @param packageId
     * @param colorId
     * @return com.yonyou.cyxdms.basedata.client.domains.vo.ColorCacheVO
     * @author renwd
     * @since 2019/9/10
     */
    @Override
    public ColorCacheVO getValueByColorId(String packageId, String colorId) {
        ClientInfoDTO loginInfoDto = ApplicationContextHelper.getBeanByType(ClientInfoDTO.class);
        String messageFormat = MessageFormat.format(BaseDataCommonConstants.COLOR_CACHE_COLORID, loginInfoDto.getAppId(), loginInfoDto.getOwnerCode());
        String field = assembleStr(packageId, colorId);
        Object colorlData = redisClient.hget(messageFormat, field);
        if (null == colorlData) {
            // 重新加载这个id值的数据
            Map<String, Object> stringObjectMap = ConditionMapUtils.conditionMap(loginInfoDto.getAppId(), loginInfoDto.getOwnerCode());
            stringObjectMap.put("packageId", packageId);
            stringObjectMap.put("colorId", colorId);
            loadValueIfNotExists(stringObjectMap, messageFormat);
            Object redisModelData = redisClient.hget(messageFormat, field);
            if (null == redisModelData) {
                return null;
            }
            return JSONUtil.jsonToObj(JSONUtil.objectToJson(redisModelData), ColorCacheVO.class);
        } else {
            return JSONUtil.jsonToObj(JSONUtil.objectToJson(colorlData), ColorCacheVO.class);
        }
    }

    /**
     * 根据配置id、选装、颜色id查询颜色信息
     */
    @Override
    public ColorCacheCMSVO getValueByColorIdCMS(String packageId, String optionId, String colorId, String trimColor) {
        ClientInfoDTO loginInfoDto = ApplicationContextHelper.getBeanByType(ClientInfoDTO.class);
        String messageFormat = MessageFormat.format(BaseDataCommonConstants.COLOR_CACHE_COLORID, loginInfoDto.getAppId(), loginInfoDto.getOwnerCode());
        String field = assembleStrCMS(packageId, colorId, trimColor);
        Object colorlData = redisClient.hget(messageFormat, field);
        if (null == colorlData) {
            // 重新加载这个id值的数据
            Map<String, Object> stringObjectMap = ConditionMapUtils.conditionMap(loginInfoDto.getAppId(), loginInfoDto.getOwnerCode());
            stringObjectMap.put("packageId", packageId);
            stringObjectMap.put("optionId", optionId);
            stringObjectMap.put("colorId", colorId);
            stringObjectMap.put("trimColor", trimColor);
            //loadValueIfNotExists(stringObjectMap, messageFormat);
            loadValueIfNotExistsCMS(stringObjectMap, messageFormat);
            Object redisModelData = redisClient.hget(messageFormat, field);
            if (null == redisModelData) {
                return null;
            }
            return JSONUtil.jsonToObj(JSONUtil.objectToJson(redisModelData), ColorCacheCMSVO.class);
        } else {
            return JSONUtil.jsonToObj(JSONUtil.objectToJson(colorlData), ColorCacheCMSVO.class);
        }
    }

    private void loadValueIfNotExistsCMS(Map<String, Object> queryByMap, String messageFormat) {
        List<ColorCacheCMSVO> colorDtoResponse = baseDataCommonClient.queryColorBySqlCMS(queryByMap).getData();
        logger.info("feign查询Color信息:{}", colorDtoResponse);

        if (!CommonUtils.isNullOrEmpty(colorDtoResponse)) {
            colorDtoResponse.stream().forEach(colorCacheDto -> initOneValueCMS(colorCacheDto, messageFormat));
        }
    }

    /**
     * 查询数据
     *
     * @param queryByMap
     * @author renwd
     * @since 2018/12/18
     */
    private void loadValueIfNotExists(Map<String, Object> queryByMap, String messageFormat) {
        List<ColorCacheVO> colorDtoResponse = baseDataCommonClient.queryColorBySql(queryByMap).getData();
        logger.info("feign查询Color信息:{}", colorDtoResponse);

        if (!CommonUtils.isNullOrEmpty(colorDtoResponse)) {
            colorDtoResponse.stream().forEach(colorCacheDto -> initOneValue(colorCacheDto, messageFormat));
        }
    }

    private void initOneValueCMS(ColorCacheCMSVO colorCache, String key) {
        String field = assembleStrCMS(colorCache.getPackageId() == null ? "" : colorCache.getPackageId().toString(), colorCache.getColorId() == null ? "" : colorCache.getColorId().toString(), colorCache.getTrimColor() == null ? "" : colorCache.getTrimColor().toString());
        redisClient.hsetExpire(key, field, JSONUtil.objectToJson(colorCache), BaseDataCommonConstants.EXPIRE_TIME_ONE_DAY);
    }

    /**
     * 数据放置redis
     *
     * @param colorCache
     * @author renwd
     * @since 2018/12/18
     */
    private void initOneValue(ColorCacheVO colorCache, String key) {
        String field = assembleStr(colorCache.getPackageId(), colorCache.getColorId());
        redisClient.hsetExpire(key, field, JSONUtil.objectToJson(colorCache), BaseDataCommonConstants.EXPIRE_TIME_ONE_DAY);
    }

    /**
     * 拼接字符串
     *
     * @param packageId 配置id
     * @param colorId   颜色id
     * @return java.lang.String
     * @author renwd
     * @since 2019/2/28
     */
    private String assembleStr(Object packageId, Object colorId) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(packageId);
        stringBuilder.append(",");
        stringBuilder.append(colorId);
        return stringBuilder.toString();
    }

    private String assembleStrCMS(String packageId, String colorId, String trimColor) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(packageId);
        stringBuilder.append(",");
        stringBuilder.append(colorId);
        if (!StringUtils.isNullOrEmpty(trimColor)) {
            stringBuilder.append(",");
            stringBuilder.append(trimColor);
        }
        return stringBuilder.toString();
    }

    /**
     * 获取所有颜色
     *
     * @param colorType 16081002 外饰色,16081001内饰色
     * @return:
     * @auther: tanjie
     * @since: 2019/11/4
     */
    @Override
    public List<ColorCacheVO> getAllColorByAppIdAndType(String appId, Integer colorType) {
        String messageFormat = MessageFormat.format(BaseDataCommonConstants.COLOR_CACHE_COLOR_APPID_COLORTYPE, appId,
                colorType);

        //ClientInfoDTO loginInfoDto = ApplicationContextHelper.getBeanByType(ClientInfoDTO.class);
        Object colorDtoResponse = redisClient.get(messageFormat);
        if (null == colorDtoResponse) {
            // 查询所有数据
            List<ColorCacheVO> colorCacheVOS =
                    baseDataCommonClient.getAllColorByAppIdAndType(appId, colorType).getData();
            logger.info("feign查询series信息:{}", colorCacheVOS);
            if (!CommonUtils.isNullOrEmpty(colorCacheVOS)) {
                redisClient.set(messageFormat, JSONUtil.objectToJson(colorCacheVOS),
                        BaseDataCommonConstants.EXPIRE_TIME_ONE_DAY);
            }
            Object redisColorDto = redisClient.get(messageFormat);
            if (null == redisColorDto) {
                return null;
            }
            return JSONUtil.jsonToList(JSONUtil.objectToJson(redisColorDto), ColorCacheVO.class);
        } else {
            return JSONUtil.jsonToList(JSONUtil.objectToJson(colorDtoResponse), ColorCacheVO.class);
        }

    }
}
